<script setup lang="ts">
import { nextTick, reactive, ref, toRaw } from "vue";
import {
  onLoad,
  onPageScroll,
  onReachBottom,
  onUnload,
} from "@dcloudio/uni-app";
import { useList } from "@/hooks/page";
import { travel_agency_task_index_list_api } from "@/package/square/api/new_guide";
import { autoTask } from "@/utils/timer";
import { Date } from "@/utils/date";
import { numToDay } from "@/utils/number";
import { Storage } from "@/utils/database";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import PageSticky from "@/components/page/sticky.vue";
import SearchBar from "./components/search-bar.vue";
import ListEmpty from "@/components/list/empty.vue";
import ListTaskItem from "./components/list-task-item.vue";

const historyKey = "square-task-search-history";

onLoad(() => {
  historyList.value = Storage.getSync<string[]>(historyKey) || [];

  autoTaskStop = autoTask({ delay: 1000, immediate: true }, () => {
    const timestamp = Date.timestamp;

    listData.value = listData.value.map((i) => {
      if (i.is_emergency === 1 && i.start_time > timestamp) {
        // 急单才有倒计时
        i.start_time_arr = numToDay(i.start_time - timestamp).split(":");
      }
      return i;
    });
  });
});
onPageScroll(() => (listLoadMore.value = listData.value.length > 1));
onReachBottom(() => loadMoreList());
onUnload(() => autoTaskStop?.());

const queryData = reactive({ keyword: "" });

const searchStatus = ref<"init" | "finish">("init"); // search：搜索中（聚焦）, finish：搜索完成
const searchClick = (type: "search" | "clear") => {
  if (type === "search") {
    const keyword = queryData.keyword.trim();
    if (!keyword) return;
    Toast.showLoading();
    reloadList()
      .then((resp) => {
        searchStatus.value = "finish";
        Toast.hideLoading();

        nextTick(() => {
          const _historyList = historyList.value;
          const index = _historyList.indexOf(keyword);
          if (index !== -1) _historyList.splice(index, 1);
          _historyList.unshift(keyword);
          historyList.value = _historyList.splice(0, 10);
          Storage.setSync(historyKey, toRaw(historyList.value));
        });
      })
      .catch(() => Toast.hideLoading());
  } else {
    queryData.keyword = "";
    searchStatus.value = "init";
  }
};

const historyList = ref<string[]>([]);
const historyClick = (key: string) => {
  if (key === "del") {
    historyList.value = [];
    Storage.deleteSync(historyKey);
  } else {
    queryData.keyword = key;
    searchClick("search");
  }
};

const taskClick = (index: number) => {
  Router.navigateTo(
    `/package/require/pages/detail/index?id=${listData.value[index].id}`
  );
};

const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: 1, page_size: 10 }, (query) => {
    return travel_agency_task_index_list_api({
      ...query,
      ...toRaw(queryData),
      type: 0,
    });
  });

let autoTaskStop: (() => void) | undefined = undefined;
</script>

<template>
  <PageSticky>
    <SearchBar v-model="queryData.keyword" @search="searchClick" />
  </PageSticky>

  <view class="search-init" v-if="searchStatus === 'init'">
    <template v-if="historyList.length !== 0">
      <view class="search-init-title">搜索历史</view>
      <image
        class="search-init-del"
        src="/static/search-del.png"
        @click="historyClick('del')"
      />
      <view class="search-init-wrapper">
        <view
          class="search-init-keyword"
          v-for="i of historyList"
          :key="i"
          @click="historyClick(i)"
        >
          {{ i }}
        </view>
      </view>
    </template>
  </view>
  <template v-else>
    <view class="search-empty" v-if="listData.length === 0">
      <ListEmpty text="暂无找到相关任务" />
    </view>
    <view class="search-data" v-else>
      <view class="search-data-wrapper">
        <view
          class="search-data-item"
          v-for="(i, d) of listData"
          :key="i.id"
          @click="taskClick(d)"
        >
          <ListTaskItem :info="i" />
        </view>
      </view>
      <ListMore v-if="listLoadMore" :status="listStatus" />
    </view>
  </template>
</template>

<style lang="scss">
.search-init {
  position: relative;
  padding-top: 28rpx;

  .search-init-title {
    padding-left: 30rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    color: #2d2d2d;
    line-height: 40rpx;
    font-weight: bold;
  }

  .search-init-del {
    position: absolute;
    top: 34rpx;
    right: 30rpx;
    width: 24rpx;
    height: 28rpx;
  }

  .search-init-wrapper {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    padding-left: 30rpx;
    padding-bottom: 24rpx;
  }

  .search-init-keyword {
    padding: 0 26rpx;
    margin-right: 24rpx;
    margin-bottom: 24rpx;
    font-size: 28rpx;
    color: #333333;
    line-height: 60rpx;
    border-radius: 36rpx;
    background-color: #ffffff;
  }
}

.search-empty {
  height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
}

.search-data {
  .search-data-wrapper {
    padding-top: 20rpx;
  }

  .search-data-item {
    margin: 0 20rpx 20rpx;
  }
}
</style>